/**
 * @ Author 何涛
 * @ Date 2016/02/19 01:09:14
 */

gpNamespace.LoadLayer = cc.Layer.extend({
    buttonLayer: null,
    myLogType: null,

    ctor: function () {
        this._super();
        cc.log("###################进入loadLayer!#####################");
        cc.log("###################进入loadLayer!#####################");
        cc.log("###################进入loadLayer!#####################");
        this.init();
    },

    init: function () {
        var effect = cc.sys.localStorage.getItem(gpNamespace.EFFECTSOUND);
        if (effect == null || effect == "") {
            cc.sys.localStorage.setItem(gpNamespace.EFFECTSOUND, 50);
            gpNamespace.SoundManager.setEffectVolumn(50);
        }
        else {
            gpNamespace.SoundManager.setEffectVolumn(parseInt(effect));
        }
        var music = cc.sys.localStorage.getItem(gpNamespace.MUSICSOUND);
        if (music == null || music == "") {
            cc.sys.localStorage.setItem(gpNamespace.MUSICSOUND, 50);
            gpNamespace.SoundManager.setMusicVolume(50);
        }
        else {
            gpNamespace.SoundManager.setMusicVolume(parseInt(music));
        }

        cc.log("effect:" + effect + "- music:" + music);

        this.initWebsocket();
    },

    //初始化websocket
    initWebsocket: function () {
        /*xinyou.netManager.init();
        xinyou.netManager.initGameSocket(ht_serverInfo.ip, ht_serverInfo.port);
        xzgbNamespace.NetManager.getInstance();*/
        xinyou.netManager.init();
//      xinyou.netManager.initGameSocket("192.168.1.90", "8080/sfqq/websocket");
//        xinyou.netManager.initGameSocket("192.168.1.90", "80/MRSK/websocket");http://115.159.39.184:6060/sfqq/do/LoginOauth
        xinyou.netManager.initGameSocket("115.159.39.184", "6060/sfqq/websocket");
//      xinyou.netManager.initGameSocket("192.168.1.123", "8080/sfqq/websocket");
    },

    onEnter: function () {
    	this._super();
    	cc.spriteFrameCache.addSpriteFrames(gpNamespace.mainSenceFirstRes.MainSenceFirst_plist);
    	cc.spriteFrameCache.addSpriteFrames(gpNamespace.loadRes.Load_plist);

        //背景
        var background = new cc.Sprite(gpNamespace.mainSenceFirst.Background);
        background.attr({
            x: cc.winSize.width / 2,
            y: cc.winSize.height / 2
        });
        this.addChild(background);

        var buttonLayer = new cc.Layer();
        background.addChild(buttonLayer);
        this.buttonLayer = buttonLayer;

        //等待中
        var armature = new ccs.Armature("loading_001u");
        armature.getAnimation().playWithIndex(0);
        armature.getAnimation().setSpeedScale(1);
        armature.setScale(1);
        armature.setAnchorPoint(0.5, 0.5);
        armature.setPosition(cc.winSize.width / 2, cc.winSize.height / 2);
        this.addChild(armature);

        var self = this;
        pluginManager.initAnySDK(function (isSucceed) {
            if (isSucceed) {
                // 显示登录按钮，让用户授权登录
                if (pluginManager.isFunctionSupported("isTokenValid")) {
                    if (pluginManager.isTokenValid()) {
                        self.login();
                    } else {
                        CocosPlay.log("isTokenInvalid !!!");
                        self.showLoginMenu();
                        //break;
                    }
                } else {
                    self.showLoginMenu();
                }
            } else {
                Utils.showToast("AnySDK初始化失败");
            }
        });
    },

    loginCallback: function (code, msg) {
        CocosPlay.log("on user result action.");
        CocosPlay.log("code: " + code);
        CocosPlay.log("msg: " + msg);

        switch (code) {
            //case anysdk.UserActionResultCode.kInitSuccess:
            //    Utils.showToast("用户插件初始化成功");
            //    break;
            //case anysdk.UserActionResultCode.kInitFail:
            //    Utils.showToast("用户插件初始化失败");
            //    break;
            case anysdk.UserActionResultCode.kLoginSuccess:
                Utils.showToast("登录成功");
                if (g_env === CocosRuntimeEnv.TENCENT) {
                    var msgObj = JSON.parse(msg);
                    pluginManager.x5_setToken({
                        "qbopenid": msgObj["qbopenid"],
                        "refreshToken": msgObj["refreshToken"],
                        "loginType": msgObj["loginType"],
                        "nickName": msgObj["nickName"]
                    });
                    // todo: 由于腾讯只有在登录的时候会返回用户信息，在refreshtoken的时候是不会返回用户信息的，所以登录完成的时候需要保存用户信息
                    cc.sys.localStorage.setItem("userInfo", msg);
                }
                // 获取用户信息
                if (pluginManager.isFunctionSupported("getUserInfo")) {
                    pluginManager.getUserInfo(this.loginCallback.bind(this));
                } else {
                    var userId = pluginManager.getUserID();
                    CocosPlay.log("userID :" + userId);
                    // 获取用户信息成功，进入游戏
                    this.showGameEntry();
                }
                break;
            case anysdk.UserActionResultCode.kLoginFail:
            	Utils.showToast("登录失败");
                this.showLoginMenu();
                break;
            case anysdk.UserActionResultCode.kLoginCancel:
            	Utils.showToast("登录被取消");
                this.showLoginMenu();
                break;
            case anysdk.UserActionResultCode.kLoginNetworkError:
            	Utils.showToast("登录网络错误");
                this.showLoginMenu();
                break;
            case anysdk.UserActionResultCode.kGetUserInfoSuccess:
                Utils.showToast("获取用户数据成功");
                var msgObj = JSON.parse(msg);
                CocosPlay.log("userInfo :" + msg);

                var qqHeadImgUrl = msgObj["avatarUrl"];

                if (qqHeadImgUrl != null && qqHeadImgUrl.length > 0) {
                    var qqNickName = msgObj["nickName"].toString().substring(0, 6);
                    var qq = qqHeadImgUrl.substring(qqHeadImgUrl.indexOf("&nk=") + 4, qqHeadImgUrl.indexOf("&s="));
                    var realUrl = qqHeadImgUrl.replace(/\\/, '');

                    gpNamespace.QQInfo.QQ = qq;
                    gpNamespace.QQInfo.NICKNAME = qqNickName;
                    gpNamespace.QQInfo.HEADURL = realUrl;
                }
                else {
                    var uin = msgObj["uin"];
                    var wxHeadImgUrl = msgObj["baseinfo"]["headurl"];
                    var wxNickName = msgObj["baseinfo"]["nick"].toString().substring(0, 6);
                    var wx = msgObj["uid"];
                    if (uin != null && uin.length > 4)
                        wx = uin;
                    var realUrl = wxHeadImgUrl.replace(/\\/, '');

                    gpNamespace.QQInfo.QQ = wx;
                    gpNamespace.QQInfo.NICKNAME = wxNickName;
                    gpNamespace.QQInfo.HEADURL = realUrl;
                }

                cc.log("getLoginType:" + pluginManager.getLoginType());

                // 获取用户信息成功，进入游戏
                this.showGameEntry();
                break;
            case anysdk.UserActionResultCode.kGetUserInfoFail:
                Utils.showToast("获取用户数据失败");
                //pluginManager.getUserInfo();
                break;
            case anysdk.UserActionResultCode.kLogoutSuccess:
                Utils.showToast("注销成功");
                this.showLoginMenu();
                break;
            case anysdk.UserActionResultCode.kLogoutFail:
                Utils.showToast("注销失败");
                this.showLoginMenu();
                break;
            default :
                Utils.showToast("未知返回码: " + code);
        }
    },

    // 登录
    login: function (sender) {
        if (sender && sender.loginType != null) {
            pluginManager.setLoginType(sender.loginType);
        }
        pluginManager.login(this.loginCallback.bind(this));
    },

    showLoginMenu: function () {
        this.buttonLayer.removeAllChildren();
        var loginItemList = [];
        var winSize = cc.winSize;
        var self = this;
        var initLoginItemList = function () {
            //var exitLabel = new cc.LabelTTF("退出", "Arial", 38);
            //var exitItem = new cc.MenuItemLabel(exitLabel, self.exitGame, self);
            //loginItemList.push(exitItem);
            if (loginItemList.length > 0) {
                var menu = new cc.Menu(loginItemList);
                menu.attr({
                    x: winSize.width / 2,
                    y: winSize.height / 6
                });
                menu.alignItemsHorizontallyWithPadding(200);
                self.buttonLayer.addChild(menu);
            }
        };
        switch (g_env) {
            case CocosRuntimeEnv.ANYSDK:
                if (pluginManager.isFunctionSupported("getAvailableLoginType")) {
                    pluginManager.getAvailableLoginType({}, function (code, msg) {
                        if (code === anysdk.UserActionResultCode.kGetAvailableLoginTypeSuccess) {
                            Utils.showToast("获取可登录类型成功");
                            var msgObj = JSON.parse(msg);
                            var result = msgObj["result"];
                            if (result === 0) {
                                var loginTypes = msgObj["loginTypes"];
                                for (var pos in loginTypes) {
                                    if (loginTypes[pos]["loginType"] == "qq") {
                                        var qqSprite = new cc.Sprite("#load_001u.png");
                                        var qqSprite1 = new tyNamespace.maskSprite("#load_001u.png");
                                        var qqLogin = new cc.MenuItemSprite(qqSprite, qqSprite1, self.login, self);
                                        qqLogin.loginType = "qq";
                                        self.myLogType = "qq";
                                        loginItemList.push(qqLogin);
                                    } else if (loginTypes[pos]["loginType"] == "wx") {
                                    	var wxSprite = new cc.Sprite("#load_002u.png");
                                    	var wxSprite1 = new tyNamespace.maskSprite("#load_002u.png");
                                        var wechatLogin = new cc.MenuItemSprite(wxSprite, wxSprite1, self.login, self);
                                        wechatLogin.loginType = "wx";
                                        self.myLogType = "wx";
                                        loginItemList.push(wechatLogin);
                                        //} else if (loginTypes[pos]["loginType"] == "guest") {
                                        //    var guestLoginLabel = new cc.LabelTTF("游客登录", "Arial", 38);
                                        //    //var guestLoginItem = new cc.MenuItemLabel(guestLoginLabel, self.guestLogin, self);
                                        //    var guestLoginItem = new cc.MenuItemLabel(guestLoginLabel, self.login, self);
                                        //    guestLoginItem.loginType = "guest";
                                        //    loginItemList.push(guestLoginItem);
                                    } else {
                                        CocosPlay.log("未知的登录类型：" + loginTypes[pos]["loginType"]);
                                    }
                                }
                            } else {
                                var anySDKLoginLabel = new cc.LabelTTF("登录", "Arial", 38);
                                //var anySDKLoginItem = new cc.MenuItemLabel(anySDKLoginLabel, self.anysdkLogin, self);
                                var anySDKLoginItem = new cc.MenuItemLabel(anySDKLoginLabel, self.login, self);
                                loginItemList.push(anySDKLoginItem);
                            }
                            initLoginItemList();
                        } else if (code === anysdk.UserActionResultCode.kGetAvailableLoginTypeFail) {
                            Utils.showToast("获取可登录类型失败");
                        } else {
                            Utils.showToast("未知错误，错误码" + code);
                        }
                    });
                } else {
                    var anySDKLoginLabel = new cc.LabelTTF("登录", "Arial", 38);
                    //var anySDKLoginItem = new cc.MenuItemLabel(anySDKLoginLabel, this.anysdkLogin, this);
                    var anySDKLoginItem = new cc.MenuItemLabel(anySDKLoginLabel, this.login, this);
                    loginItemList.push(anySDKLoginItem);
                    initLoginItemList();
                }
                break;
        }
    },

    // 退出游戏
    exitGame: function () {
        switch (g_env) {
            case CocosRuntimeEnv.LIEBAO:
            case CocosRuntimeEnv.BAIDU:
                CocosPlay.log("this channel not allow game exit");
                break;
            default :
                cc.director.end();
                break;
        }
    },

    // 登录成功后，显示进入游戏按钮
    showGameEntry: function () {
    	this.buttonLayer.removeAllChildren();
    	console.log("##################showGameEntry#onEnter!#####################");
    	console.log("##################showGameEntry#onEnter!#####################");
    	console.log("##################showGameEntry#onEnter!#####################");

//        gpNamespace.preloadPlaza();
        cc.director.runScene(new gpNamespace.GpMainScene());

        var functionList = [];
        var winSize = cc.winSize;
        var gameEntryLabel = new cc.LabelTTF("进入游戏", "Arial", 38);
        var gameEntryItem = new cc.MenuItemLabel(gameEntryLabel, function () {
        	cc.director.runScene(new gpNamespace.GpMainScene());
        }, this);
        functionList.push(gameEntryItem);
        if (pluginManager.isFunctionSupported("logout")) {
            var logoutLabel = new cc.LabelTTF("登出", "Arial", 38);
            var logoutItem = new cc.MenuItemLabel(logoutLabel, this.logout, this);
            functionList.push(logoutItem);
        }
        var gameEntryMenu = new cc.Menu(functionList);
        gameEntryMenu.attr({
            x: winSize.width / 2,
            y: winSize.height / 2
        });
        gameEntryMenu.alignItemsVerticallyWithPadding(10);
        this.buttonLayer.addChild(gameEntryMenu);
    },

    // 登出
    logout: function () {
        pluginManager.logout(this.loginCallback.bind(this));
    }
});

var registerKeyEvent = function () {
//    CocosPlay.log("registerKeyEvent");
    cc.eventManager.addListener(cc.EventListener.create({
        event: cc.EventListener.KEYBOARD,
        onKeyReleased: function (keyCode, event) {
            if (cc.sys.isNative) {
                cc.Dialog.show("确定退出游戏吗？", function (dialog) {
                    cc.director.end();
                }, function (dialog) {
                    cc.log("取消退出游戏");
                });
            }
        }
    }), -1);
};
registerKeyEvent();